package com.xmb.wcapi.controller;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xmb.wcapi.constant.R;
import com.xmb.wcapi.constant.WarehouseStatusConstant;
import com.xmb.wcapi.entity.Inventory;
import com.xmb.wcapi.entity.StockNow;
import com.xmb.wcapi.exception.InterfaceErrorException;
import com.xmb.wcapi.service.IInventoryService;
import com.xmb.wcapi.util.ShiroUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huangping
 * @since 2024-04-12
 */
@Controller
@RequestMapping("manage/inventory")
public class InventoryController {

    @Autowired
    private IInventoryService inventoryService;

    @GetMapping("/addHtml")
    public String addHtml(Model model){
        return "inventory/add";
    }

    @GetMapping("/show")
    public String show(){
        return "inventory/show";
    }

    /**
     * 重新调整库存
     */
    @PostMapping("/reloadInvSum")
    @ResponseBody
    public R reloadInvSum(String day){
        if (StringUtils.isEmpty(day)){
            return R.error("重新结转日期未接收到参数！");
        }
        try {
            inventoryService.reloadInvSum(day);
        } catch (InterfaceErrorException e) {
            return R.error(e.getMsg());
        }
        return R.ok();
    }

    @RequestMapping("/upload")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public R upload(String data) {
        if (StringUtils.isEmpty(data)) {
            return R.error("未读取到数据");
        }
        // 去除第一列表头
        JSONArray objects = JSONUtil.parseArray(data);
        objects.remove(0);

        List<Inventory> list = JSONUtil.toList(objects, Inventory.class);
        // 数据去重
        Map<String, String> collect = new ArrayList<>(list.stream()
                .collect(Collectors.toMap(
                        p -> Arrays.asList(p.getMaterial(),p.getStoreType()), // 为多属性创建键
                        p -> p, // 原对象为值
                        (existing, replacement) -> existing // 冲突时保留现有对象
                ))
                .values())
                .stream()
                .collect(Collectors.toMap(k -> k.getMaterial() +"_zbc_"+ k.getStoreType(), Inventory::getGrowUp));
        // 截取key
        Set<String> stringSet = collect.keySet().stream().map(k -> k.substring(0, k.indexOf("_zbc_"))).collect(Collectors.toSet());

        // 获取查询数据
        List<Inventory> inventories = inventoryService.list(Wrappers.lambdaQuery(Inventory.class).in(Inventory::getMaterial, stringSet));

        // 组装需要修改的数据
        for (Inventory inventory : inventories) {
            String key = inventory.getMaterial()+ "_zbc_" + inventory.getStoreType();
            inventory.setGrowUp(collect.get(key));
            //移除 已经使用的 key
            collect.remove(key);
        }

        inventoryService.updateBatchById(inventories);

        // 判断是否还存在未修改的数据
        List<Inventory> newInvList = new ArrayList<>();
        for (String key : collect.keySet()) {
            // key拆分
            String ma = key.substring(0, key.indexOf("_zbc_"));

            Inventory inventory = new Inventory();
            inventory.setCreateUser(ShiroUtil.getUserId());
            inventory.setCreateTime(new Date());
            inventory.setMaterial(ma);
            inventory.setCusCode("02002");
            inventory.setCusName("纬创资通（成都）有限公司");
            inventory.setStandard("10");
            inventory.setGrowUp(collect.get(key));

            String stockType = key.substring(key.indexOf("_zbc_") + 5);
            inventory.setStoreType(stockType);
            inventory.setStoreName(WarehouseStatusConstant.getMessage(stockType));

            newInvList.add(inventory);

        }

        inventoryService.saveBatch(newInvList);

        return R.ok();
    }

}

